<?php
require_once 'db.php';

// 接收表单数据
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

// 定义响应数据
$response = [
    'status' => false,
    'message' => '注册失败'
];

// 验证输入
if (empty($username) || empty($password)) {
    $response['message'] = '用户名和密码不能为空';
    echo json_encode($response);
    exit;
}

// 验证用户名长度 (6-20位)
if (strlen($username) < 6 || strlen($username) > 20) {
    $response['message'] = '用户名长度应在6-20位之间';
    echo json_encode($response);
    exit;
}

// 验证密码长度 (6-20位)
if (strlen($password) < 6 || strlen($password) > 20) {
    $response['message'] = '密码长度应在6-20位之间';
    echo json_encode($response);
    exit;
}

// 检查用户名是否已存在
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    $response['message'] = '用户名已存在，请更换用户名';
    echo json_encode($response);
    exit;
}

// 密码加密 (使用password_hash)
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

// 插入用户数据
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $hashedPassword);

if ($stmt->execute()) {
    $response['status'] = true;
    $response['message'] = '注册成功';
} else {
    $response['message'] = '注册失败，请稍后再试';
}

echo json_encode($response);

// 关闭连接
$stmt->close();
$conn->close();
?>